package com.sky.Task;

import cn.mybatis.mp.core.sql.executor.chain.QueryChain;
import com.sky.entity.*;
import com.sky.mapper.*;
import com.sky.service.EmailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.List;

/**
 * 定时任务：检查并更新图书逾期状态
 */
@Slf4j
@Component
public class BooksTASK {

    @Autowired
    private UserborrowhistoryMapper userborrowhistoryMapper;

    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private EmailService emailService;

    /**
     * 每天凌晨0点执行图书逾期检查任务
     */
    @Scheduled(cron = "0 0 0 * * ?")
    @Transactional
    public void BookOverdueDateModification() {
        log.info("开始执行图书逾期检查任务...");

        try {
            // 查询所有未归还的借阅记录（状态为"借阅中"）
            List<Userborrowhistory> borrowHistories = QueryChain.of(userborrowhistoryMapper)
                    .eq(Userborrowhistory::getStatus, "借阅中")
                    .list();

            // 获取当前日期
            LocalDate currentDate = LocalDate.now();

            for (Userborrowhistory history : borrowHistories) {
                // 获取应还日期
                LocalDate dueDate = history.getDueDate().toInstant()
                        .atZone(ZoneId.systemDefault())
                        .toLocalDate();

                // 计算逾期天数
                long overdueDays = ChronoUnit.DAYS.between(dueDate, currentDate);

                // 如果逾期天数大于0，更新借阅历史记录
                if (overdueDays > 0) {
                    history.setOverdueDays((int) overdueDays);
                    userborrowhistoryMapper.update(history);
                    log.info("更新借阅记录逾期天数 - 借阅ID: {}, 逾期天数: {}", 
                            history.getBorrowHistoryId(), overdueDays);
                }
            }

            log.info("图书逾期检查任务执行完成");
        } catch (Exception e) {
            log.error("图书逾期检查任务执行失败", e);
        }
    }
}
